<template>
  <div class="search">
    <el-form :inline="true" :model="formSearch" class="demo-form-inline">
      <el-form-item label="图片名称">
        <el-input v-model="formSearch.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="发布状态">
        <el-select v-model="formSearch.show" placeholder="请选择状态">
          <el-option label="全部" value="null" />
          <el-option label="已发布" value="1" />
          <el-option label="未发布" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="图片分类">
        <el-select v-model="formSearch.type" placeholder="请选择分类">
          <el-option label="全部" value="null" />
          <el-option
            v-for="type in types.data"
            :key="type.id"
            :label="type.tname"
            :value="type.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="success" @click="openDialog">上传图片</el-button>
      </el-form-item>
    </el-form>
  </div>
  
  <div class="table">
    <el-table :data="tableData.data" style="width: 100%">
      <el-table-column prop="purl" label="图片" width="380" align="center">
        <template #default="scope">
          <el-popover placement="right" width="600px" trigger="hover">
            <template #reference>
              <a :href="scope.row.purl">{{scope.row.purl}}</a>
            </template>
            <a v-show="show" :href="scope.row.purl" target="_blank">
                <el-image fit="contain" :src="scope.row.purl" @load="load"
            /></a>
            <el-icon v-show="!show" class="is-loading"  style="font-size: 32px;"><icon-loading style="height:2rem;width:2rem;" /></el-icon>
        </el-popover>
          <!-- <div class="demo-image">
            <div class="block">
              <a :href="scope.row.purl" target="_blank">
                <el-image style="width: 100%"   :src="scope.row.purl"
              /></a>
            </div>
          </div> -->
        </template>
      </el-table-column>
      <el-table-column prop="pname" width="250" label="名称" align="center" />
      <el-table-column prop="type" width="100" label="类型" align="center" />
      <el-table-column
        prop="createtime"
        label="上传时间"
        width="180"
        align="center"
      />
      <el-table-column prop="pshow" label="发布状态" width="80" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.show" @change="showChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column
        prop="pauthor"
        label="来源者"
        width="100"
        align="center"
      />
      <el-table-column prop="ccount" label="热度量" width="80" align="center" />
      <el-table-column prop="dcount" label="下载量" width="80" align="center" />
      <el-table-column fixed="right" label="操作" width="250" align="center">
        <template #default="scope">
          <el-button link type="warning" size="small" @click="openDialogWithId(scope.row.id)"
            ><i class="iconfont icon-xiugai"></i>修改</el-button
          >
          <el-popconfirm
            title="确定删除吗？"
            confirm-button-text="是"
            cancel-button-text="不是"
            :hide-icon="true"
            @confirm="delConfirm(scope.row.id)"
          >
            <template #reference>
              <el-button link type="danger" size="small"
                ><i class="iconfont icon-changyonggoupiaorenshanchu"></i
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="example-pagination-block">
    <el-pagination
      layout="prev, pager, next"
      :page-size="size"
      v-model:current-page="page"
      :total="total"
      @current-change="currentChange"
      @prev-click="preClick"
      @next-click="nextClick"
    />
  </div>
  <PictureDialog
    :form="form"
    :dialogForm="dialogForm"
    :types="types.data"
    @getFormData="getFormData"
    @changeDialog="closeDialog"
    @submitForm="submitForm"
  ></PictureDialog>
</template>

<script setup>
import { ref, reactive, provide, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import api from "@/axios";
import { Loading as IconLoading } from '@element-plus/icons-vue'

const router = useRouter();
const formSearch = reactive({});
let tableData = reactive({ data: [] });
let total = ref(0);
let page = ref(1);
let size = ref(7);
let show = ref(false);
let types = reactive({ data: [] });
const dialogForm = reactive({
  title: "",
  show: false,
  formLabelWidth: "60px",
  draggable: true,
});
const form = reactive({
  pname: "",
  cover: "",
  pauthor: "",
  ptype:"",
  id:''
});
let config = {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
    };

const load = ()=>{
  show.value = true
}
//打开添加对话框
const openDialog = () => {
  dialogForm.title = "上传图片";
  dialogForm.show = true;
};

//关闭添加对话框
const closeDialog = () => {
  dialogForm.show = false;
  form.pname = "";
  form.cover = "";
  form.pauthor = "";
  form.ptype = "";
  form.id = ''
};

//打开更新对话框
const openDialogWithId = (id) => {
  dialogForm.title = "更新图片";
  getPictureById(id);
  dialogForm.show = true;
};
//获取图片地址
const getUrlImage = (url) => {
  console.log(url)
  form.cover = url;
};
//获取表单值
const getFormData = (name, val) => {
  form[name] = val;
};


//获取对应的blog分类
const getPictureById = async (id) => {
  let result = await api({
    method: "get",
    url: "/picture/get?id=" + id,
  });
  if (result) {
    let { id, pauthor, pname, purl, ptype } = result;
    form.pname = pname;
    form.cover = purl;
    form.pauthor = pauthor;
    form.ptype = ptype;
    form.id = id;
  }
};

//提交表单
const submitForm = () => {
  let { pname, ptype, cover, pauthor,id } = form;
  if(cover==null && cover ==""){
    ElMessage({
      message: "图片为上传！",
      type: "error",
    });
    return
  }
  if(ptype==null && ptype ==""){
    ElMessage({
      message: "类型为选择！",
      type: "error",
    });
    return
  }
  if (id) {
    updatePicture(pname, ptype, cover,pauthor,id);
  } else {
    addPicture(pname, ptype, cover,pauthor);
  }
};

//添加图片
const addPicture = async(pname, ptype, cover,pauthor)=>{
  try {
    await api.post("/picture/save",{pname, ptype, purl:cover,pauthor},config);
    ElMessage({
      message: "上传成功！",
      type: "success",
    });
    dialogForm.show = false;
    getToPage(page.value);
  } catch (error) {
    ElMessage({
      message: "上传失败！",
      type: "error",
    });
  }
  
}

//更新图片
const updatePicture = async(pname, ptype, cover,pauthor,id)=>{
  console.log(pname, ptype, cover,pauthor,id)
  try {
    await api.post("/picture/update",{pname, ptype, purl:cover,pauthor,id},config);
    ElMessage({
      message: "更新成功！",
      type: "success",
    });
    dialogForm.show = false;
    getToPage(page.value);
  } catch (error) {
    ElMessage({
      message: "更新失败！",
      type: "error",
    });
  }
  
}

const currentChange = (val) => {
  getToPage(val);
  page.value = val;
};
const preClick = (val) => {
  getToPage(val - 1);
  page.value = val - 1;
};
const nextClick = (val) => {
  getToPage(val + 1);
  page.value = val + 1;
};
const showChange = (item) => {
  let pshow = item.show ? 1 : 0;
  let id = item.id;
  setShow(id, pshow);
};
const search = ()=>{
  getToPage(1);
}

const delConfirm = async (id) => {
  try {
    await api.post("/picture/set/clean", { id, isclean: 1 }, config);
    ElMessage({
      message: "删除成功！",
      type: "success",
    });
    getToPage(page.value);
  } catch (error) {
    ElMessage({
      message: "删除失败！",
      type: "error",
    });
  }
};

const getToPage = async (page) => {
  let result = await api(`/picture/page?page=${page}&size=${size.value}`+((formSearch.title != ""&&formSearch.title!=undefined)?`&pname=${formSearch.title}`:'')+((formSearch.type != 'null'&&formSearch.type!=undefined)?`&ptype=${formSearch.type}`:'')+((formSearch.show != 'null'&&formSearch.show!=undefined)?`&pshow=${formSearch.show}`:''));
  total.value = result.total;
  result = result.list.map((item) => {
    for (let type of types.data) {
      if (type.id == item.ptype) {
        item.type = type.tname;
      }
    }
    item.show = item.pshow == 0 ? false : true;
    return item;
  });
  tableData.data = result;
};

const getTypes = async () => {
  let result = await api("/ptype/all");
  types.data = result;
};

const setShow = async (id, pshow) => {
  try {
    await api.post("/picture/set/type", { id, pshow }, config);
    if (pshow) {
      ElMessage({
        message: "发布成功！",
        type: "success",
      });
    } else {
      ElMessage({
        message: "取消成功！",
        type: "info",
      });
    }
  } catch (error) {
    ElMessage({
      message: "发布失败！",
      type: "error",
    });
  }
};

onBeforeMount(() => {
  getTypes();
  getToPage(page.value);
});

provide("openDialogWithId", openDialogWithId);
provide("closeDialog", closeDialog);
provide("getUrlImage", getUrlImage);
</script>

<style lang="scss" scoped>
.search {
  min-width: 1200px;
}
.example-pagination-block {
  margin-top: 10px;
}
.el-table .cell {
    max-height: 230px !important;
}
el-popover{
  max-width: 800px;
}
</style>